package logic

import (
	"context"
	"errors"
	"github.com/eeppee_admin/clouddisk/service/model"
	"github.com/eeppee_admin/clouddisk/service/helper"
	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShareCreateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewShareCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShareCreateLogic {
	return &ShareCreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ShareCreateLogic) ShareCreate(req *types.ShareCreateRequest, userIdentity string) (resp *types.ShareCreateResponse, err error) {
	uuid := helper.UUID()
	us := new(model.UserStore)
	has, err := l.svcCtx.Engine.Where("identity = ?", req.UserStoreIdentity).
		Get(us)
	if err != nil {
		return nil, err
	}

	if !has {
		return nil, errors.New("用户存储没找到")
	}

	data := &model.ShareTable{
		Identity: uuid,
		UserIdentity: userIdentity,
		UserStoreIdentity: req.UserStoreIdentity,
		StoreIdentity: us.StoreIdentity,
		ExpiredTime: req.ExpiredTime,
	}

	_, err = l.svcCtx.Engine.Insert(data)
	if err != nil {
		logx.Error(err)
		return
	}

	resp = new(types.ShareCreateResponse)
	resp.Identity = uuid

	return
}
